// filters/AuthFilter.h
#pragma once
#include <drogon/drogon.h>
#include <jwt-cpp/jwt.h>

class AuthFilter : public drogon::HttpFilter<AuthFilter> {
public:
    virtual void doFilter(const HttpRequestPtr& req,
                         FilterCallback&& fcb,
                         FilterChainCallback&& fccb) override {
        
        std::string token;
        
        // 1. 从 Authorization header 获取
        auto authHeader = req->getHeader("Authorization");
        if (!authHeader.empty() && authHeader.find("Bearer ") == 0) {
            token = authHeader.substr(7);
        } 
        // 2. 从 cookie 获取
        else {
            token = req->getCookie("token");
        }

        if (token.empty()) {
            // 未认证，继续执行但不在请求属性中设置用户信息
            fccb();
            return;
        }

        try {
            // 验证 JWT token
            auto decoded = jwt::decode(token);
            auto verifier = jwt::verify()
                .allow_algorithm(jwt::algorithm::hs256{"your-secret-key"})
                .with_issuer("auth0");
            
            verifier.verify(decoded);
            
            // 将用户信息存储在请求对象中
            auto user_id = decoded.get_payload_claim("user_id").as_string();
            req->getAttributes()->insert("user_id", user_id);
            
            fccb();
            
        } catch (const std::exception& e) {
            LOG_DEBUG << "Token verification failed: " << e.what();
            // token 验证失败，继续执行但不在请求属性中设置用户信息
            fccb();
        }
    }
};